from PyQt4.QtGui import * 
from PyQt4.QtCore import * 

class AnimationPanel(QWidget):
    def __init__(self, sprite, parent=None):
        QWidget.__init__(self, parent)
        self.set_sprite(sprite)
        self.timer = QTimer()
        self.current_frame = 0
        self.connect(self.timer, SIGNAL("timeout()"), self.tick)
        self.set_playpause(True)
    
    def set_sprite(self, sprite):
        self.sprite = sprite
        self.current_frame = 0
        self.resize(sprite.width, sprite.height)
        self.setMinimumSize(sprite.width + 2, sprite.height + 2)
        self.setMaximumSize(sprite.width + 2, sprite.height + 2)
        self.update()
        
    def set_playpause(self, setting):
        if setting:
	        self.timer.start(50)
        else:
	        self.timer.stop()

    def tick(self):
        self.update()
        if self.current_frame < len(self.sprite.frames):
	        self.current_frame = self.current_frame + 1
        else:
	        self.current_frame = 0

    def paintEvent(self, ev):
        p = QPainter(self)
        p.fillRect(self.rect(),QBrush(QColor("white")))
        
        if self.current_frame >= len(self.sprite.frames):
            self.current_frame = 0
            
        pen = QPen(QColor(200,200,200))
        p.setPen(pen)
        p.drawRect(0,0,self.rect().width()-1,self.rect().height()-1)

        for layer in self.sprite.frames[self.current_frame].layers:
            p.drawPixmap(1, 1, layer)
        
        del p
